package managers;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HttpsURLConnection;

import twitter4j.internal.org.json.JSONObject;

public class HashManager {
	

 	private String salt = new String();
 	private final String USER_AGENT = "Mozilla/5.0";

	

 	
 // HTTP GET request that retrieve the token
 		public String obtainToken(String schemaName, String secretKey) throws Exception {
 			
 		System.setProperty("jsse.enableSNIExtension", "false");
 		
 			JSONObject answerJson;			
 			String url = "https://www.gamify.ws/api/v1/salt/"+schemaName;  	 
 			URL obj = new URL(url);			
 			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
 			con.setRequestMethod("GET");
  			con.setRequestProperty("User-Agent", USER_AGENT);

 	 		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
 			String inputLine;
 			StringBuffer responseBuffer = new StringBuffer();
 			 
 			while ((inputLine = in.readLine()) != null) {
 				responseBuffer.append(inputLine);
 			}			
 			in.close();	
 	 
 			String response = responseBuffer.toString();
 			
 			// obtaining the salt 
 			answerJson = new JSONObject(response);
 			
 			if (answerJson.has("data")){
 				answerJson = answerJson.getJSONObject("data");
 				
 				if (answerJson.has("salt")){
 						salt = answerJson.getString("salt");
 						}
 				}
 			
 			// the token is given by the sha1 of the concatenation of the salt and the API secret
 			String token = new String(secretKey+salt);
 			String sha = sha1(token);
 			
 			return sha;
 			}
 			
 	   //compute the sha1 of a string
 	   public static String sha1(String input) throws NoSuchAlgorithmException {
 	       MessageDigest mDigest = MessageDigest.getInstance("SHA1");
 	       byte[] result = mDigest.digest(input.getBytes());
 	       StringBuffer sb = new StringBuffer();
 	       for (int i = 0; i < result.length; i++) {
 	           sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
 	       }
 	        
 	       return sb.toString();
 	   }

}
